const grpc = require('@grpc/grpc-js');
const { message_proto } = require('./proto')
const const_module = require('./const')
const { v4: uuidv4 } = require('uuid');
// const emailModule = require('./email');
const redis_module = require('./redis')

async function GetVarifyCode(call, callback) {
    console.log("email is ", call.request.email)
    try{
        //尝试从数据库获取验证码
        let query_res = await redis_module.GetRedis(const_module.code_prefix + call.request.email)
        console.log("query res is ", query_res)
        let uniqueId = query_res;
        //如果数据库中没有查到验证码，则生成新的验证码并保存到redis中
        if(query_res ==null){
            uniqueId = uuidv4();
            if (uniqueId.length > 4) {
                uniqueId = uniqueId.substring(0, 4);
            } 

            //设置验证码过期时间
            let bres = await redis_module.SetRedisExpire(const_module.code_prefix + call.request.email, uniqueId, 600)
            if(!bres){
                callback(null, { email:  call.request.email,
                    error:const_module.Errors.RPCFailure,
                    msg:'nodejs SetRedisExpire error'
                });
                return;
            }
        }

        console.log("uniqueId is ", uniqueId)
        let text_str =  '您的验证码为'+ uniqueId +'请三分钟内完成注册'
        console.log("text_str is ", text_str)
        //发送邮件
        // let mailOptions = {
        //     from: 'lalala@123.com',
        //     to: call.request.email,
        //     subject: '验证码',
        //     text: text_str,
        // };

        // let send_res = await emailModule.SendMail(mailOptions);
        // console.log("send res is ", send_res)

        // 模拟邮箱发送成功
        callback(null, { email:  call.request.email,
            code:const_module.Errors.Success,
            msg:'success'
        }); 
    }catch(error){
        console.log("catch error is ", error)
        callback(null, { email:  call.request.email,
            code:const_module.Errors.RPCFailure,
            msg:'fail'
        }); 
    }
}

function main() {
    var server = new grpc.Server()
    server.addService(message_proto.VarifyService.service, { GetVarifyCode: GetVarifyCode })
    server.bindAsync('0.0.0.0:50051', grpc.ServerCredentials.createInsecure(), () => {
        console.log('grpc server started')        
    })
}

main()